<template>
<div class="organize-structure full-height page-content padding-b-20 padding-t-20 content">
  <div class="margin-l-20 q-mb-md">
    <!--<q-btn class="margin-r-10" outline color="primary" label="下载模板" type="a" :href="templateUrl" download />-->
    <!--<q-btn class="margin-r-10" outline color="primary" label="批量导入" >-->
      <!--<input type="file" @change="importFile($event)" multiple class="q-uploader__input overflow-hidden absolute-full"-->
             <!--accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">-->
    <!--</q-btn>-->
    <q-btn @click="openAddOrEditDialog('add')" outline color="primary" label="添加组织" class="qa-btn"/>
<!--    <q-space />-->
<!--    <q-input outlined dense class="quik-search" placeholder="员工编码/工位名称"-->
<!--             v-model="searchVal" @keyup.enter="search(value)" >-->
<!--      <template v-slot:prepend>-->
<!--        <q-icon name="iconfont icontubiao-21" color="#999" style="font-size: 20px" />-->
<!--      </template>-->
<!--    </q-input>-->
<!--    <q-btn class="q-ml-md" unelevated color="primary" label="查询" />-->
  </div>
  <q-table
    :data="tableData" :columns="columns"
    row-key="id" class="scroll myTable-line"
    :loading="tableLoading" table-style="max-height: 100%"
    :hide-bottom="!!tableData.length" :pagination="{rowsPerPage: 0}">
    <template v-slot:body="props">
      <transition name="fade">
        <q-tr :props="props" v-show="props.row.show || props.row.level === 2" v-if="props.row.label!=='default'">
          <q-td key="label" :props="props" :style="{'padding-left': (props.row.level-2)*20+16+'px', 'width': '30%'}">
            <q-btn :class="{'invisible': props.row.childrenCount===0}"
                   dense round flat size="sm"
                   :icon="props.row.expand ? 'iconfont icontubiao-40' : 'iconfont icontubiao-43'"
                   @click="toggleChildren(props.row)" />
            {{ props.row.label }}
          </q-td>
          <q-td key="workshopProperty" :props="props">{{ props.row.workshopProperty === null || props.row.workshopProperty === undefined ? '全部' : props.row.workshopPropertyName}}</q-td>
          <q-td key="parentName" :props="props">{{ props.row.parentName }}</q-td>
          <q-td key="leveldesc" :props="props">{{ props.row.leveldesc }}</q-td>
          <q-td key="remark" :props="props">{{ props.row.remark || '--' }}</q-td>
          <q-td key="operate" :props="props" style="width: 100px">
            <table-btn btnType="other" icon="icontubiao-50" tooltip="添加子项" @click="addChild(props.row)" :class="{'invisible': props.row.level===4}"/>
            <table-btn btnType="edit" @click="openAddOrEditDialog('edit', props.row)"/>
            <table-btn btnType="delete" :disable="!!props.row.locationNum" @click="delDialog(props.row)" :tips="`确定要删除${props.row.label}吗？`"/>
          </q-td>
        </q-tr>
      </transition>
    </template>
  </q-table>
  <!--  添加编辑弹框-->
  <add-edit-dialog ref="addEditDialog" :org-list="orgClassList" @submit="submit"></add-edit-dialog>
</div>
</template>

<script>
import { getOrganize, addOrganize, editOrganize, delOrganize } from 'src/boot/factory/organize'
import AddEditDialog from './components/add-edit-organize-dialog'
export default {
  name: 'organize-structure',
  data () {
    return {
      orgClassList: [
        {
          label: '分厂',
          value: 1
        },
        {
          label: '车间',
          value: 2
        },
        {
          label: '产线',
          value: 3
        },
        {
          label: '设备组',
          value: 4
        }
      ], // 组织层级数据
      // 筛选
      searchVal: '', // 搜索值
      templateUrl: '../../statics/file/company.xls', // 企业信息模板地址
      // table
      tableLoading: false, // table加载时使用
      tableData: [], // table数据
      columns: [ // 所有标题
        { name: 'label', align: 'left', label: '所在位置', field: 'label', check: true },
        { name: 'workshopProperty', align: 'left', label: '车间属性', field: 'workshopProperty', check: true },
        { name: 'parentName', align: 'left', label: '上级组织', field: 'parentName', check: true },
        { name: 'leveldesc', align: 'left', label: '组织层级', field: 'leveldesc', check: true },
        { name: 'remark', align: 'left', label: '备注', field: 'remark', check: true },
        { name: 'operate', align: 'center', label: '操作', field: 'operate', check: true }
      ]
    }
  },
  created () {
    this.getInfo()
  },
  methods: {
    // 初始化数据
    getInfo () {
      this.getList()
    },
    // 获取表结构
    getList () {
      this.tableLoading = true
      getOrganize().then(res => {
        this.tableData = this.initInfo(res.data)
      }).finally(() => {
        this.tableLoading = false
      })
    },
    // 给数据添加show、expand、isFirst、isLast、 index属性
    initInfo (data) {
      let info
      if (this.tableData.length === 0) {
        info = data.map((item, index) => {
          const isLast = index === data.length - 1 ||
            (index !== 0 && item.parentId === data[index - 1].parentId && item.parentId !== data[index + 1].parentId) ||
            (index !== 0 && data[index - 1].id + '' === item.parentId + '' && data[index - 1].childrenCount === 1)
          // const isLast = index === data.length - 1 || item.level !== data[index + 1].level
          return {
            ...item,
            show: item.parentLevel === 0 && item.parentName === '/',
            expand: false,
            isFirst: index === 0 || item.parentId + '' === data[index - 1].id + '',
            isLast: isLast,
            index: index,
            parentId: item.parentId,
            id: item.id
          }
        })
      } else {
        info = data.map((item, index) => {
          let tableItem = this.tableData.find(f => {
            return f.hash === item.hash
          })
          const isLast = index === data.length - 1 ||
            (index !== 0 && item.parentId === data[index - 1].parentId && item.parentId !== data[index + 1].parentId) ||
            (index !== 0 && data[index - 1].id + '' === item.parentId + '' && data[index - 1].childrenCount === 1)
          let parent = this.tableData.find(child => {
            return item.parentLevel === child.level && item.parentName === child.label && item.parentHash.indexOf(child.hash) > -1
          })
          return {
            ...item,
            show: tableItem ? tableItem.show : parent ? parent.expand : item.parentLevel === 0 && item.parentName === '/',
            expand: item.childrenCount === 0 ? false : tableItem ? tableItem.expand : false,
            isFirst: index === 0 || item.parentId + '' === data[index - 1].id + '',
            isLast: isLast,
            index: index,
            parentId: item.parentId,
            id: item.id
          }
        })
      }
      return info
    },
    // 显示隐藏子集
    toggleChildren (item) {
      item.expand = !item.expand
      let children
      if (item.expand) {
        children = this.findOneChild(item)
      } else {
        children = this.findChild(item.hash)
      }
      const hashs = children.map(item => {
        return item.hash
      })
      this.tableData.forEach(i => {
        if (hashs.includes(i.hash)) {
          i.show = item.expand
        }
      })
    },
    // 找到下面一级子级
    findOneChild (parent) {
      const data = JSON.parse(JSON.stringify(this.tableData))
      let children = data.filter((item) => {
        return item.parentLevel === parent.level && item.parentName === parent.label && item.parentHash.indexOf(parent.hash) > -1
      })
      let child = this.findExpandChild(children)
      children = children.concat(child)
      return children
    },
    // 找到展开的子级
    findExpandChild (arr) {
      let result = []
      arr.forEach(item => {
        if (item.expand) {
          let child = this.findOneChild(item)
          result = result.concat(child)
        }
      })
      return result
    },
    // 找到下面的所有子集id
    findChild (hash) {
      const data = JSON.parse(JSON.stringify(this.tableData))
      let child = data.filter((item) => {
        return item.parentHash === hash
      })
      child.forEach(item => {
        if (item.childrenCount > 0) {
          const newArr = this.findChild(item.hash)
          child = child.concat(newArr)
        }
      })
      return child
    },
    // 打开添加编辑弹框
    openAddOrEditDialog (state = 'add', item) {
      this.$refs.addEditDialog.showDialog(state, item)
    },
    addChild (item) {
      const info = {
        ...item,
        label: null,
        parentName: item.label,
        parentId: item.id,
        leveldesc: null,
        remark: ''
      }
      this.$refs.addEditDialog.showDialog('child', info)
    },
    // 提交添加编辑弹框
    submit (state, param, info) {
      let ids, params
      switch (state) {
        case 'add':
          ids = this.getAddParamsId(param.level)
          params = {
            ...param,
            ...ids
          }
          addOrganize(params).then(res => {
            this.getList()
            this.$refs.addEditDialog.hideDialog()
            this.$message.success(`添加${param.name}成功`)
          }).finally(() => {
            this.$refs.addEditDialog.submitting = false
          })
          break
        case 'child':
          ids = this.getAddChildParamsId(param.level, info)
          console.log(ids)
          params = {
            ...param,
            ...ids,
            parentLevel: info.level
          }
          addOrganize(params).then(res => {
            this.getList()
            this.$refs.addEditDialog.hideDialog()
            this.$message.success(`添加${param.name}成功`)
          }).finally(() => {
            this.$refs.addEditDialog.submitting = false
          })
          break
        case 'edit':
          params = {
            ...param,
            parentLevel: info.parentLevel,
            workshopId: info.workshopId,
            lineId: info.lineId
          }
          editOrganize(param).then(res => {
            this.getList()
            this.$refs.addEditDialog.hideDialog()
            this.$message.success(`编辑${param.name}成功`)
          }).finally(() => {
            this.$refs.addEditDialog.submitting = false
          })
          break
      }
    },
    // 添加组织，查找plantId、workshopId、lineId
    getAddParamsId (state) {
      let params = {}
      let defaultItem1, defaultItem2, defaultItem3
      // defaultItem1 = this.tableData.find(item => {
      //   return item.label === 'default' && item.parentId === '0'
      // })
      // defaultItem2 = this.tableData.find(item => {
      //   return item.label === 'default' && item.parentHash === defaultItem1.hash
      // })
      // defaultItem3 = this.tableData.find(item => {
      //   return item.label === 'default' && item.parentHash === defaultItem2.hash
      // })
      switch (state + '') {
        case '2':
          defaultItem1 = this.tableData.find(item => {
            return item.label === 'default' && item.parentId + '' === '0'
          })
          params = {
          }
          break
        case '3':
          defaultItem1 = this.tableData.find(item => {
            return item.label === 'default' && item.parentId + '' === '0'
          })
          defaultItem2 = this.tableData.find(item => {
            return item.label === 'default' && item.parentHash === defaultItem1.hash
          })
          params = {
            lineId: defaultItem2.id
          }
          break
        case '4':
          defaultItem1 = this.tableData.find(item => {
            return item.label === 'default' && item.parentId + '' === '0'
          })
          defaultItem2 = this.tableData.find(item => {
            return item.label === 'default' && item.parentHash === defaultItem1.hash
          })
          defaultItem3 = this.tableData.find(item => {
            return item.label === 'default' && item.parentHash === defaultItem2.hash
          })
          params = {
            lineId: defaultItem2.id,
            workshopId: defaultItem3.id
          }
          break
      }
      return params
    },
    // 添加子组织，查找plantId、workshopId、lineId
    getAddChildParamsId (state, info) {
      let params = {}, plantItem, workshopItem, lineItem
      const parentItem = this.tableData.find(item => {
        return item.hash === info.hash
      })
      switch (state + '') {
        case '2':
          params = {
            plantId: parentItem.id
          }
          break
        case '3':
          if (parentItem.level === 2) {
            workshopItem = parentItem
          } else if (parentItem.level === 1) {
            plantItem = parentItem
            workshopItem = this.tableData.find(item => {
              return item.label === 'default' && item.parentHash === plantItem.hash
            })
          }
          params = {
            workshopId: workshopItem.id
          }
          break
        case '4':
          if (parentItem.level === 3) {
            // 无默认/一种默认/两种默认的情况都有
            lineItem = parentItem
            workshopItem = this.tableData.find(item => {
              return item.hash === lineItem.parentHash
            })
            plantItem = this.tableData.find(item => {
              return item.hash === workshopItem.parentHash
            })
          } else if (parentItem.level === 2) {
            // 一种默认的情况
            workshopItem = parentItem
            plantItem = this.tableData.find(item => {
              return item.hash === workshopItem.parentHash
            })
            lineItem = this.tableData.find(item => {
              return item.label === 'default' && item.parentHash === workshopItem.hash
            })
          } else if (parentItem.level === 1) {
            // 两种默认的情况
            plantItem = parentItem
            workshopItem = this.tableData.find(item => {
              return item.label === 'default' && item.parentHash === plantItem.hash
            })
            lineItem = this.tableData.find(item => {
              return item.label === 'default' && item.parentHash === workshopItem.hash
            })
          }
          params = {
            workshopId: workshopItem.id,
            lineId: lineItem.id
          }
          break
      }
      return params
    },
    // 删除弹框
    delDialog (item) {
      const params = {
        id: item.id,
        level: item.level
      }
      delOrganize(params).then(() => {
        this.$message.success(`删除${item.label}成功`)
        this.getList()
      })
    },
    // 批量导入上传文件
    importFile (event) {
      // this.$q.loading.show()
      // importFile(event.target.files).then((res) => {
      //   this.$q.loading.hide()
      //   this.$q.dialog({
      //     title: '提示',
      //     message: res.message
      //   })
      // })
    }
  },
  components: {
    AddEditDialog
  }
}
</script>

<style scoped lang="stylus">
.organize-structure{
  background-color #fff
  .myTable .q-table__middle{
    max-height calc(100% - 42px)
  }
}
</style>
